package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.DoubleButtonDialog;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *  商品浏览记录
 */
public class BrowsingHistoryActivity extends BackableTitleBarActivity implements OnLoadDataActionListener,OnItemLongClickListener{
	@ViewInject(id = R.id.browing_empty_relat) RelativeLayout mEmptyRelat;


	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;

	private BrowsingHistoryAdapter mAdapter;
	private DoubleButtonDialog mDoubleDialog;
	private List<Product> mProducts;
	private int nowPage = 1;
	private Handler mHandler  = new MyHandler(this);


	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_browsing_history);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_browsing_history);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.browsing_history_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mRefreshListView.getRefreshableView().setOnItemLongClickListener(this);
		mAdapter = new BrowsingHistoryAdapter(this, R.layout.item_browsing_history);
		mRefreshListView.setAdapter(mAdapter);
		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);

		mLoadMoreProxy.refreshing();

		setListOnClick();

	}

	@Override
	public void onRefresh(int page) {
		updateBrowsingList(1, true);
	}

	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateBrowsingList(nowPage, false);
	}


	/**
	 * 请求分页的参数
	 * @param pageNum
	 * @param isRefresh
	 */
	private void updateBrowsingList(final int pageNum,final boolean isRefresh){

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(BrowsingHistoryActivity.this);

					PageEntity<Product> entry = client.getBrowseList(pageNum, 20, "", "asc");
					int totlePage = entry.getTotalPages();

					mProducts = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mProducts = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mProducts = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

	}
	
	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				
				switch (msg.what){
				case 0:
					mAdapter.update(mProducts);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(mProducts);
					mRefreshListView.onRefreshComplete();
					break;
				default:
					break;
				}
				
			}
		}
	}
	

	private void setListOnClick() {
		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View paramView, int position, long paramLong) {

				Intent intent = new Intent(BrowsingHistoryActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID",mAdapter.getData().get(position-1).getId()+"");
				startActivity(intent);

			}

		});

	}

	/* 适配器 */
	public class BrowsingHistoryAdapter extends AbsViewHolderAdapter<Product>{

		public BrowsingHistoryAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {

			ImageView mImageView = getViewFromHolder(R.id.item_browsing_history_image);
			TextView mNameTextView = getViewFromHolder(R.id.item_browsing_history_name_txt);
			TextView mPriceTextView = getViewFromHolder(R.id.item_browsing_history_price_txt);

			ImageLoader.getInstance().displayImage(itemData.getImage(),mImageView);
			mNameTextView.setText(itemData.getName());
			mPriceTextView.setText("￥"+itemData.getPrice());
		}

	}
	/* 顶部视图 */
	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		titleBar.setRightButtonText(R.string.title_browsing_history_remove);
		titleBar.setOnRightButtonClickListener(new OnClickListener() {
			@Override
			public void onClick(View paramView) {
				showDeleteDialog(-1);
			}
		});
	}


	private void showDeleteDialog(final int pos) {

		dismissDeleteDialog();
		mDoubleDialog = new DoubleButtonDialog(this);
		
		if (pos == -1) {
			mDoubleDialog.showDialog(getString(R.string.info_is_clean_all_history), new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					new Thread(){
						public void run() {
							try {
								PageEntity<Product> entry = WebClient.getInstance(BrowsingHistoryActivity.this).deleteAllBrowse();
								mProducts = entry.getContent();

							} catch (WebException e) {
								if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
									mProducts = null;
								else
									e.printStackTrace();
							}
							mHandler.sendEmptyMessage(0);
						};
					}.start();

				}
			});
		}else {
			
			mDoubleDialog.showDialog(getString(R.string.info_is_delete_item), new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					new Thread(){
						public void run() {
							try {
								PageEntity<Product> mEntity = WebClient.getInstance(BrowsingHistoryActivity.this).deleteBrowse(mAdapter.getData().get(pos).getId());
								mProducts = mEntity.getContent();

							} catch (WebException e) {
								if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
									mProducts = null;
								else
									e.printStackTrace();
							}
							mHandler.sendEmptyMessage(0);
						};
					}.start();

				}
			});
			
		}
	}

	private void dismissDeleteDialog() {

		if( mDoubleDialog != null && mDoubleDialog.isShowing() ) {
			mDoubleDialog.dismiss();
		}
		mDoubleDialog = null;

	}
	@Override
	protected void onDestroy() {
		dismissDeleteDialog();
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent,
			View view, int position, long id) {

		showDeleteDialog(position-1);

		return true;
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		onRefresh(1);
	}





}
